﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ImLxp.Domain.Abstraction
{
    public abstract class ValueObject
    {
        protected static bool EqualOperator(ValueObject left,ValueObject right)
        {
            //^异或运算符，当且仅当只有一个操作为true时，结果才为true
            if (Object.ReferenceEquals(left, null) ^ Object.ReferenceEquals(right, null))
                return false;
            return Object.ReferenceEquals(left, null) || left.Equals(right);
        }

        protected static bool NotEqualOperator(ValueObject left,ValueObject right)
        {
            return !EqualOperator(left, right);
        }

        /// <summary>
        /// 获取原子值
        /// </summary>
        /// <returns></returns>
        protected abstract IEnumerable<object> GetAtomicValues();

        public override bool Equals(object obj)
        {
            if (obj == null || obj.GetType() != this.GetType())
                return false;

            ValueObject other = (ValueObject)obj;
            IEnumerator<object> thisValues = this.GetAtomicValues().GetEnumerator();
            IEnumerator<object> otherValues = other.GetAtomicValues().GetEnumerator();

            while (thisValues.MoveNext() && otherValues.MoveNext())
            {
                if (ReferenceEquals(thisValues.Current, null) ^ ReferenceEquals(otherValues.Current, null))
                    return false;

                if (thisValues.Current != null && !otherValues.Current.Equals(otherValues.Current))
                    return false;
            }

            return !thisValues.MoveNext() && !otherValues.MoveNext();
        }

        public override int GetHashCode()
        {
            return GetAtomicValues()
                .Select(x => x != null ? x.GetHashCode() : 0)
                .Aggregate((x, y) => x ^ y);
        }
    }
}
